package com.chen.util;

import jdk.nashorn.internal.runtime.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class DistributeLockUtil {
    private static final String LOCK_ID = "distributeLockId";
    private static final int LOCK_TIME = 3;
    private static final TimeUnit LOCK_TIME_UNIT = TimeUnit.MINUTES;

    @Autowired
    private RedisTemplate redisTemplate;

    public String getLock(){
        String lockValue = UUID.randomUUID().toString().replace("-","").toLowerCase();
        boolean success = redisTemplate.opsForValue().setIfAbsent(LOCK_ID,lockValue,LOCK_TIME,LOCK_TIME_UNIT);
        if (success){
            log.info("创建分布式锁成功");
            return lockValue;
        }
        log.warn("分布式锁已存在");
        return null;
    }

    public boolean releaseLock(String lockValue){
        DefaultRedisScript redisScript = new DefaultRedisScript();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lock.lua")));
        redisScript.setResultType(Long.class);
        Long result = (Long) redisTemplate.execute(redisScript, Collections.singletonList(LOCK_ID),lockValue);
        if (result.equals(1L)){
            log.info("分布式锁已正常释放");
            return true;
        }else {
            log.error("分布式锁释放失败");
            return false;
        }
    }
}
